from lxml import etree
import json

# 修复linux下面导入包不存在问题
import os
import sys

curPath = os.path.abspath(os.path.dirname(__file__))
rootPath = os.path.split(curPath)[0]
sys.path.append(rootPath)

# 载入相应的包
from miner_firmware_version.all_function import *
from miner_firmware_version.config import *

new_firmware_list = []
firmware_list = list(read_firmwarre('all_miner_firmware_version.txt'))

# GET bitmain firmware version
# api的数据是字符串，要转换成json
bitmain_firmware_version_api = json.loads(get_url_html(bitmain_url))

# JSON.data[0].children[0].children[0].fileName
if bitmain_firmware_version_api["code"] == '0':
    for btc_miners in bitmain_firmware_version_api['data']:
        for btc_miner in btc_miners['children']:

            for miner_info in btc_miner['children']:
                firmware = miner_info['fileName']
                firewarr_name = firmware.split('-')[0:2]
                if 'pdf' in firmware or firewarr_name[1:2] == []:
                    continue
                else:
                    new_firmware_list.append(firmware)
else:
    print('参数错误')

# GET bitmain firmware version
whatsminer_html = get_url_html(whatsminer_url)

whatsminer_html=etree.HTML(whatsminer_html)
M20x_M30x_firmware_version = whatsminer_html.xpath('//*[@id="app"]/div/div/div/div/div[2]/div/div[2]/div[1]/a/span/text()')
M10x_fireware_version = whatsminer_html.xpath('//*[@id="app"]/div/div/div/div/div[4]/div/div[2]/div[1]/a/span/text()')

# 创初始数据
new_firmware_list.append(M20x_M30x_firmware_version[0])
new_firmware_list.append(M10x_fireware_version[0])

# GET awalon firmware version

avalon_html = get_url_html(awalon_url)

avalon_html = etree.HTML(avalon_html)
A1066_firmware_version = avalon_html.xpath('//*[@id="1"]/div/div[4]/div[4]/text()')
A1047_firmware_version = avalon_html.xpath('//*[@id="1"]/div/div[5]/div[4]/text()')

new_firmware_list.append('A1066_' + A1066_firmware_version[0])
new_firmware_list.append('A1047_' + A1047_firmware_version[0])

# 重写固件版本文件
# re_write_firmware(firmware_list)

# test
# new_firmware_list.append('这是测试数据22322')

if __name__ == '__main__':
    if not judgement_firmware_version(new_firmware_list, firmware_list):
        str_new_firmware = ''
        for new_firmware in new_firmware_list:
            if new_firmware not in firmware_list:
                print('{}'.format(new_firmware))
                str_new_firmware += new_firmware + '\n'
        send_message('有新固件更新！\n\n{}\n请及时安排测试更新'.format(str_new_firmware))
        re_write_firmware(new_firmware_list)
    else:
        message = '蚂蚁矿机/神马矿机/阿瓦隆新机型官方没有新固件'
        send_message(message)